package org.zachary.agent.infrastructure.utils;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.zachary.agent.domain.aggregate_model.loginUser.LoginUser;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SecurityUtil {
    //获取当前用户信息
    public LoginUser getCurrentUser(){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication!=null && authentication.getPrincipal() instanceof LoginUser){
            return (LoginUser) authentication.getPrincipal();
        }
        return null;
    }

    //获取用户ID
    public String getCurrentUserID(){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication!=null && authentication.getPrincipal() instanceof LoginUser){
            return ((LoginUser) authentication.getPrincipal()).getUsername();
        }
        return null;
    }

    //获取当前用户权限
    public List<String> getCurrentUserPermission(){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        return authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
    }

    //检查当前用户是否拥有指定权限
    public boolean hasPermission(String... permissions){
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (String permission:permissions){
            if(authorities.stream().noneMatch(authority -> authority.getAuthority().equals(permission))){
                return false;
            }
        }
        return true;
    }

}
